<template>
  <div class="user-age-chart">
    <t-loading :loading="loading">
      <div ref="chartRef" class="chart-container"></div>
      <div v-if="!loading && !data.length" class="empty-data">
        <t-empty description="暂无数据" />
      </div>
    </t-loading>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import type { UserAgeData } from '../../../api/statistics'
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必需的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  BarChart,
  CanvasRenderer
])

const props = defineProps<{
  data: UserAgeData[]
  loading: boolean
}>()

const chartRef = ref<HTMLElement | null>(null)
const chart = ref<echarts.ECharts | null>(null)

// 初始化图表
onMounted(() => {
  if (chartRef.value) {
    chart.value = echarts.init(chartRef.value)
    updateChart()
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize)
  }
})

// 组件卸载时清理
onUnmounted(() => {
  if (chart.value) {
    chart.value.dispose()
  }
  window.removeEventListener('resize', handleResize)
})

// 监听数据变化
watch(() => props.data, updateChart, { deep: true })

// 处理窗口大小变化
const handleResize = () => {
  if (chart.value) {
    chart.value.resize()
  }
}

// 更新图表
const updateChart = () => {
  if (!chart.value || !props.data.length) return
  
  // 排序数据，按年龄段顺序排列
  const sortedData = [...props.data].sort((a, b) => {
    // 提取年龄段的数字部分进行比较
    const getAgeNumber = (str: string) => {
      const match = str.match(/(\d+)/)
      return match ? parseInt(match[1]) : 0
    }
    return getAgeNumber(a.ageRange) - getAgeNumber(b.ageRange)
  })
  
  const xAxisData = sortedData.map(item => item.ageRange)
  const seriesData = sortedData.map(item => item.count)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c}人'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#E6E6E6'
        }
      },
      axisLabel: {
        color: '#666'
      }
    },
    yAxis: {
      type: 'category',
      data: xAxisData,
      axisLine: {
        lineStyle: {
          color: '#E6E6E6'
        }
      },
      axisLabel: {
        color: '#666'
      }
    },
    series: [
      {
        name: '用户数量',
        type: 'bar',
        data: seriesData,
        barWidth: 20,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
            {
              offset: 0,
              color: '#0052D9'
            },
            {
              offset: 1,
              color: '#2B91FF'
            }
          ])
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}人'
        }
      }
    ]
  }
  
  chart.value.setOption(option)
}
</script>

<style scoped>
.user-age-chart {
  width: 100%;
  height: 100%;
  position: relative;
}

.chart-container {
  width: 100%;
  height: 350px;
}

.empty-data {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style> 